<?php

App::uses('CakeSessionHandlerInterface', 'Model/Datasource/Session');
App::uses('DatabaseSession', 'Model/Datasource/Session');
App::uses('ClassRegistry', 'Utility');

class CustomSessionHandler extends DatabaseSession implements CakeSessionHandlerInterface {


/**
 * Method called on the destruction of a database session.
 *
 * @param integer $id ID that uniquely identifies session in database
 * @return boolean True for successful delete, false otherwise.
 */
	public function destroy($id) {
		CakeLog::debug("destroy: cancellazione file in cache legati alla sessione ".$id);
		Cache::delete("jobbers_".$id);
		return parent::destroy($id);
	}

	public function gc($expires = null) {
		if (!$expires) {
			$expiresNew = time();
		} else {
			$expiresNew = time() - $expires;
		}
		// elimino i file di cache associati alla sessione
		$sessions = $this->_model->find("list",array("fields"=>array($this->_model->alias . ".id", $this->_model->alias . ".expires"), "conditions"=> array($this->_model->alias . ".expires <" => $expiresNew)));
		foreach ($sessions as $key => $value) {
			CakeLog::debug("gc(".date("d/m/Y  H:i:s",$expiresNew)."): cancellazione file in cache legati alla sessione ".$key." scaduta in data ". date("d/m/Y  H:i:s",$value));
			Cache::delete("jobbers_".$key);
		}
		return parent::gc($expires);
	}


}
